package models

import (
	"time"
)

type User struct {
	ID           uint      `gorm:"primaryKey" json:"id"`
	Username     string    `gorm:"uniqueIndex;not null;size:50" json:"username"`
	PasswordHash string    `gorm:"not null;size:255" json:"-"`
	Email        string    `gorm:"uniqueIndex;size:100" json:"email"`
	Role         string    `gorm:"size:20;default:'user'" json:"role"` // 'super_admin', 'user'
	CreatedAt    time.Time `gorm:"default:now()" json:"created_at"`
	UpdatedAt    time.Time `gorm:"default:now()" json:"updated_at"`

	Devices []Device `gorm:"foreignKey:UserID" json:"devices,omitempty"`
}

type Device struct {
	ID          uint      `gorm:"primaryKey" json:"id"`
	UserID      uint      `gorm:"not null" json:"user_id"`
	DeviceID    string    `gorm:"uniqueIndex;not null;size:36" json:"device_id"` // UUID format
	Name        string    `gorm:"not null;size:100" json:"name"`
	Description string    `gorm:"type:text" json:"description"`
	DeviceType  string    `gorm:"size:20;default:'direct'" json:"device_type"` // 'direct', 'gateway'
	Status      string    `gorm:"size:20;default:'offline'" json:"status"`     // 'online', 'offline', 'error'
	LastSeen    time.Time `json:"last_seen"`
	CreatedAt   time.Time `gorm:"default:now()" json:"created_at"`
	UpdatedAt   time.Time `gorm:"default:now()" json:"updated_at"`

	User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

// DeviceTelemetry 设备遥测数据 (TimescaleDB 超表)
type DeviceTelemetry struct {
	Time          time.Time `gorm:"primaryKey;type:timestamptz;not null" json:"time"`
	DeviceID      uint      `gorm:"primaryKey;not null" json:"device_id"`
	TelemetryData JSONB     `gorm:"type:jsonb;not null" json:"telemetry_data"` // 存储完整的遥测数据JSON
}

// DeviceEvent 设备事件 (TimescaleDB 超表)
type DeviceEvent struct {
	Time      time.Time `gorm:"primaryKey;type:timestamptz;not null" json:"time"`
	DeviceID  uint      `gorm:"not null" json:"device_id"`
	EventType string    `gorm:"size:50;not null" json:"event_type"` // 'connect', 'disconnect', 'error', 'command'
	EventData JSONB     `gorm:"type:jsonb" json:"event_data"`
	CreatedAt time.Time `gorm:"default:now()" json:"created_at"`
}

// JSONB 类型用于存储 JSON 数据
type JSONB map[string]interface{}

// Scan 实现 sql.Scanner 接口
func (j *JSONB) Scan(value interface{}) error {
	// 这里需要实现 JSONB 的扫描逻辑
	// 在实际实现中，您可能需要使用 encoding/json 包
	return nil
}

// Value 实现 driver.Valuer 接口
func (j JSONB) Value() (interface{}, error) {
	// 这里需要实现 JSONB 的值转换逻辑
	// 在实际实现中，您可能需要使用 encoding/json 包
	return nil, nil
}

// MQTT 相关结构体
type MQTTTelemetryPayload struct {
	Timestamp  string                 `json:"timestamp"`
	Metrics    map[string]interface{} `json:"metrics"`
	Subdevices map[string]interface{} `json:"subdevices,omitempty"`
}

type MQTTStatusPayload struct {
	Timestamp  string                 `json:"timestamp"`
	Status     string                 `json:"status"`
	Info       map[string]interface{} `json:"info,omitempty"`
	Subdevices map[string]interface{} `json:"subdevices,omitempty"`
}

type MQTTEventPayload struct {
	Timestamp string                 `json:"timestamp"`
	EventType string                 `json:"event_type"`
	EventData map[string]interface{} `json:"event_data"`
}

type MQTTCommandPayload struct {
	CommandID  string                 `json:"command_id"`
	Timestamp  string                 `json:"timestamp"`
	Command    string                 `json:"command"`
	Target     string                 `json:"target"` // "self" or subdevice identifier
	Parameters map[string]interface{} `json:"parameters"`
}

type MQTTCommandResponsePayload struct {
	CommandID string                 `json:"command_id"`
	Timestamp string                 `json:"timestamp"`
	Status    string                 `json:"status"` // "success" or "error"
	Target    string                 `json:"target"`
	Result    map[string]interface{} `json:"result,omitempty"`
}

// API 请求/响应结构体
type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type LoginResponse struct {
	Token string `json:"token"`
	User  User   `json:"user"`
}

type CreateUserRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
	Email    string `json:"email" binding:"required,email"`
	Role     string `json:"role" binding:"required"`
}

type CreateDeviceRequest struct {
	Name        string `json:"name" binding:"required"`
	Description string `json:"description"`
	DeviceType  string `json:"device_type" binding:"required"`
}

type UpdateDeviceRequest struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

type CommandRequest struct {
	Command    string                 `json:"command" binding:"required"`
	Parameters map[string]interface{} `json:"parameters"`
}

type PaginationResponse struct {
	Page       int `json:"page"`
	PageSize   int `json:"page_size"`
	Total      int `json:"total"`
	TotalPages int `json:"total_pages"`
}

type DeviceListResponse struct {
	Devices    []Device           `json:"devices"`
	Pagination PaginationResponse `json:"pagination"`
}

type UserListResponse struct {
	Users      []User             `json:"users"`
	Pagination PaginationResponse `json:"pagination"`
}

type EventListResponse struct {
	Events     []DeviceEvent      `json:"events"`
	Pagination PaginationResponse `json:"pagination"`
}

type EventStatsResponse struct {
	TotalEvents int            `json:"total_events"`
	EventTypes  map[string]int `json:"event_types"`
	Period      struct {
		StartTime time.Time `json:"start_time"`
		EndTime   time.Time `json:"end_time"`
	} `json:"period"`
}

type TelemetryHistoryResponse struct {
	Metrics []struct {
		Name string `json:"name"`
		Data []struct {
			Time  time.Time `json:"time"`
			Value float64   `json:"value"`
		} `json:"data"`
	} `json:"metrics"`
}
